<?php

namespace app\api\controller\user;

use app\common\controller\Api;
use think\Db;
use think\Config;

//高级用户
class PowerUser extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 高级用户管理中心
     * @ApiMethod (GET)
     * @path api/user/power_user/index
     */
    public function index()
    {
        $user_id = $this->auth->id;
        $page = $this->request->param('page',1);

        $user = db('user')->field('commission_money')->where(['id'=>$user_id])->find();
        $fenxiaoTotal = db('fenxiao_log')->where(['user_id'=>$user_id,'user_del'=>'0'])->sum('price');
        $fenxiaoWithdraw = db('withdraw')->where(['user_id'=>$user_id,'status'=>1,'user_del'=>'0'])->sum('price');
        $fenxiaoWithdrawSuccess = db('withdraw')->where(['user_id'=>$user_id,'status'=>2,'user_del'=>'0'])->sum('price');
        $user['fenxiao_total'] = $fenxiaoTotal;//分销总金额
        $user['fenxiao_withdraw'] = $fenxiaoWithdraw;//提现中金额
        $user['fenxiao_withdraw_success'] = $fenxiaoWithdrawSuccess;//已提现金额
        $log = db('fenxiao_log')
            ->field('fenxiao.*,u.image,u.username')
            ->alias('fenxiao')
            ->join('user u','fenxiao.to_user_id = u.id','LEFT')
            ->where(['fenxiao.user_id'=>$user_id,'fenxiao.user_del'=>'0'])
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);
        $log = $log->toArray();
        $log['data'] = addWebSiteUrl($log['data'],['image']);
        foreach ($log['data'] AS $key => $value) {
            $log['data'][$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
        }
        $this->success('请求成功',[
            'user_info'=>$user,
            'list'=>$log
        ]);
    }

    /**
     * 我的团队
     * @ApiMethod (GET)
     * @path api/user/power_user/myTeam
     */
    public function myTeam()
    {
        $user_id = $this->auth->id;
        $page = $this->request->param('page',1);
        $keyWord = $this->request->param('key_word','');
        $where = [];
        if (!empty($keyWord)) {
            $where['username|tel'] = ['like',"%".$keyWord.'%'];
        }
        $teamTotla = db('user')->field('*')->where(['pid'=>$user_id])->count();
        $user = db('user')
            ->field('id,username,image,tel')
            ->where(['pid'=>$user_id])
            ->where($where)
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);
        $user = $user->toArray();
        $user['data'] = addWebSiteUrl($user['data'],['image']);
        foreach ($user['data'] AS $key => $value) {
            $userTwoCount = db('user')->where(['pid'=>$value['id']])->count();
            $user['data'][$key]['children'] = $userTwoCount;
        }
        $this->success('请求成功',[
            'total'=>$teamTotla,
            'list'=>$user
        ]);
    }

    /**
     * 我的二级团队
     * @ApiMethod (GET)
     * @path api/user/power_user/myTeamTwo
     */
    public function myTeamTwo()
    {
        $user_id = $this->auth->id;
        $page = $this->request->param('page',1);
        $uid = $this->request->param('uid');
        $keyWord = $this->request->param('key_word','');
        $where = [];
        if (!empty($keyWord)) {
            $where['username|tel'] = ['like',"%".$keyWord.'%'];
        }

        $teamUser = db('user')
            ->field('id,username,image')
            ->where(['id'=>$uid])
            ->find();

        $count = db('user')
            ->field('id,username,image,tel')
            ->where(['pid'=>$uid])
            ->count();

        $user = db('user')
            ->field('id,username,image,tel')
            ->where(['pid'=>$uid])
            ->where($where)
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);

        $user = $user->toArray();
        $user['data'] = addWebSiteUrl($user['data'],['image']);

        $this->success('请求成功',[
            'teamUser'=>$teamUser,
            'total'=>$count,
            'list'=>$user
        ]);
    }

    /**
     * 提现页面
     * @ApiMethod (GET)
     * @path api/user/power_user/withdraw
     */
    public function withdraw()
    {
        $user_id = $this->auth->id;
        $storeId = $this->auth->store_id;
        $page = $this->request->param('page',1);
        //1分销余额提现  2推广中心/空间余额提现  3推广合伙人余额提现  6分红余额提现
        $accountType = $this->request->get('account_type',1);
        if (empty($accountType)) {
            $this->error('未知来源');
        }

        $user = db('user')->where(['id'=>$user_id])->find();
        $store = db('store')->field('store_name,avatar')->where(['id'=>$storeId])->find();
        $store = addWebSiteUrl($store,['avatar']);
        //最低提现额
        $withdrawLowPrice = db('config')->where(['name'=>'withdraw_low','group'=>'basic'])->value('value');


        //最新提现
        $withdrawNew = db('withdraw')
            ->field('addtime')
            ->where(['user_id'=>$user_id,'type'=>$accountType,'user_del'=>'0'])
            ->where('status','in',[1,2])
            ->order('addtime DESC')
            ->value('addtime');
        $withdrawNew = date('Y-m-d H:i:s',time());

        //提现记录
        $log = db('withdraw')
            ->field('price,status,target,FROM_UNIXTIME(addtime,"%Y-%m-%d %H:%m:%s") as addtime,remark')
            ->where(['user_id'=>$user_id,'type'=>$accountType,'user_del'=>'0'])
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);

        $price = $user['commission_money'];//可提现余额
        switch ($accountType) {
            case 1:
                $price = $user['commission_money'];
                break;
            case 2:
                $price = $user['promotion_money'];
                break;
            case 3:
                $price = $user['promotion_balance'];
                break;
            case 6:
                $price = $user['bonus_balance'];
                break;
        }

        $this->success('请求成功',[
            'store'=>$store,
            'withdraw'=>[
                'price'=>$price,
                'recentDate'=>$withdrawNew,
                'price_low'=>$withdrawLowPrice
            ],
            'list'=>$log
        ]);
    }

    /**
     * 提现操作
     * @ApiMethod (GET)
     * @path api/user/power_user/withdrawOperate
     */
    public function withdrawOperate()
    {
        Db::startTrans();
        try {
            $userId = $this->auth->id;
            $storeId = $this->auth->store_id;
            $type = $this->request->post('type',1);//1=现金提现,2=提现到储值
            //1分销余额提现  2推广中心/空间余额提现  3推广合伙人余额提现  6分红余额提现
            $accountType = $this->request->post('accountType','');
            $price = $this->request->post('price',0);
            if (empty($accountType)) {
                $this->error('未知来源');
            }
            if (empty($type)) {
                $this->error('未知提现账户');
            }
            $price = trim($price);
            //最低提现额
            $withdrawLowPrice = db('config')->where(['name'=>'withdraw_low','group'=>'basic'])->value('value');
            if ($price < $withdrawLowPrice) {
                $this->error('不能低于¥'.$withdrawLowPrice);
            }
            if ($price <= 0) {
                $this->error('请输入正确提现金额');
            }

            //手续费比例
            $withdrawRate = db('config')->where(['name'=>'withdraw_rate','group'=>'basic'])->value('value');

            $user = db('user')->where('id',$userId)->lock(true)->find();

            $accountPrice = $user['commission_money'];//可提现余额
            $accountField = 'commission_money';
            switch ($accountType) {
                case 1:
                    $accountPrice = $user['commission_money'];
                    $accountField = 'commission_money';
                    break;
                case 2:
                    $accountPrice = $user['promotion_money'];
                    $accountField = 'promotion_money';
                    break;
                case 3:
                    $accountPrice = $user['promotion_balance'];
                    $accountField = 'promotion_balance';
                    break;
                case 6:
                    $accountPrice = $user['bonus_balance'];
                    $accountField = 'bonus_balance';
                    break;
            }
            if ($accountPrice < $price) {
                $this->error('余额不足');
            }

            $storeId = $accountType == 2 ? 0 : $storeId;
            //添加提现记录
            db('withdraw')->insert([
                'user_id'=>$userId,
                'to_store_id'=>$storeId,
                'price'=>$price,
                'withdraw_rate'=>$withdrawRate,
                'type'=>$accountType,
                'target'=>$type,
                'status'=>1,
                'addtime'=>time()
            ]);

            //提现扣钱，不通过再把钱加回去
            db('user')->where('id',$userId)->setDec($accountField,$price);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提现申请成功，请耐心等待工作人员审核');
    }

}
